<template>
  <div class="flex flex-col h-full overflow-hidden">
    <app-header/>

    <main>
      <h2 class="page-title">报警配置 (位对应)</h2>

      <div class="top-bar">
        <button id="btn-add-alarm-group" class="hmi-button hmi-button-primary" @click="goToAddAlarmGroupPage">
          <i class="fas fa-plus"></i> 新增地址组
        </button>
        <div class="filter-input-container">
          <i class="fas fa-search"></i>
          <input type="text" id="alarm-group-search" v-model="searchTerm" placeholder="搜索地址或类别..."
                 @input="filterAlarmGroupTable">
        </div>
      </div>

      <div class="alarm-table-container">
        <table class="alarm-table">
          <thead>
          <tr>
            <th class="col-address">地址</th>
            <th class="col-category">类别</th>
            <th v-for="i in 16" :key="`bit-header-${i-1}`" class="col-bit">Bit {{ i - 1 }}</th>
            <th class="col-actions">操作</th>
          </tr>
          </thead>
          <tbody id="alarm-group-table-body">
          <tr
              v-for="group in filteredAlarmGroups"
              :key="group.id"
              :data-group-id="group.id"
              :class="{ 'highlight': group.highlight }"
          >
            <td class="col-address">{{ group.address }}</td>
            <td class="col-category">{{ group.category || '-' }}</td>
            <td v-for="i in 16" :key="`bit-cell-${group.id}-${i-1}`" class="col-bit"
                :title="getBitTooltip(group, i - 1)">
              {{ group.bits ? (group.bits[i - 1]?.description || '') : '' }}
            </td>
            <td class="col-actions">
              <button class="action-button edit" title="编辑" @click="goToEditAlarmGroupPage(group.id)">
                <i class="fas fa-edit"></i>
              </button>
              <button class="action-button delete" title="删除"
                      @click="goToDeleteAlarmGroupConfirmPage(group.id, group.address)">
                <i class="fas fa-trash"></i>
              </button>
            </td>
          </tr>
          <tr v-if="filteredAlarmGroups.length === 0">
            <td colspan="19" class="px-3 py-4 text-center text-[var(--text-secondary)]">无匹配的报警地址组记录</td>
          </tr>
          </tbody>
        </table>
      </div>
    </main>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed, watch, onUnmounted} from 'vue';
import {useRouter} from 'vue-router'; // 导入 useRouter
// 不再需要导入 AppHeader，因为它已全局配置

const router = useRouter(); // 获取路由实例

// --- 响应式数据 ---
// 报警地址组数据 (从API获取)
const alarmGroupConfigData = reactive([]);

const searchTerm = ref(''); // 搜索输入框的值
const isLoading = ref(false); // 用于显示加载状态

// --- 计算属性 ---
// 根据搜索词过滤并高亮报警地址组列表
const filteredAlarmGroups = computed(() => {
  const lowerSearchTerm = searchTerm.value.toLowerCase();
  if (!lowerSearchTerm) {
    // 如果搜索词为空，显示所有地址组，且无高亮
    return alarmGroupConfigData.map(group => ({...group, highlight: false}));
  } else {
    // 过滤并标记高亮
    return alarmGroupConfigData.map(group => {
      let searchString = `${group.address.toLowerCase()} ${(group.category || '').toLowerCase()}`;
      if (group.bits) {
        Object.values(group.bits).forEach(bit => {
          if (bit && bit.description) {
            searchString += ` ${bit.description.toLowerCase()}`;
          }
        });
      }
      const highlight = searchString.includes(lowerSearchTerm);
      return {...group, highlight};
    }).filter(group => group.highlight); // 只显示匹配的行
  }
});


// --- 方法 ---

// 加载报警地址组数据
const loadAlarmGroups = async () => {
  isLoading.value = true;
  try {
    if (window.electronAPI) {
      const groups = await window.electronAPI.alarmGroups.getAll();
      // 清空并重新填充数组，保持响应式
      alarmGroupConfigData.splice(0, alarmGroupConfigData.length);
      if (groups && groups.length) {
        groups.forEach(group => alarmGroupConfigData.push(group));
      }
      console.log('报警地址组数据加载成功:', groups?.length || 0);
    } else {
      console.warn('未检测到Electron API，使用模拟数据');
      // 使用模拟数据（开发环境）
      setTimeout(() => {
        alarmGroupConfigData.splice(0, alarmGroupConfigData.length, ...[
          {
            id: 'group_mw8000', address: 'MW8000', category: '轴报警',
            bits: {
              0: {code: 'M710', description: '主轴左右[X1]轴伺服故障，请检查！'},
              1: {code: 'M711', description: '主轴前后[Y1]轴伺服故障，请检查！'},
              // ... 其他bits (保持现有数据结构)
            }
          },
          // ... 其他组 (保持现有数据结构)
        ]);
      }, 500);
    }
  } catch (error) {
    console.error('加载报警地址组数据失败:', error);
  } finally {
    isLoading.value = false;
  }
};

// 过滤报警地址组表格 (当 searchTerm 变化时计算属性会自动更新)
const filterAlarmGroupTable = () => {
  console.log('Filtering table with:', searchTerm.value);
  // filteredAlarmGroups 计算属性会自动更新
};

// 获取 Bit 单元格的 tooltip 文本
const getBitTooltip = (group, bitIndex) => {
  const bitConfig = group.bits ? group.bits[bitIndex] : null;
  return bitConfig ? `Bit ${bitIndex}: ${bitConfig.code || 'N/A'} - ${bitConfig.description}` : `Bit ${bitIndex}: 未配置`;
};


// 跳转到新增报警地址组页面
const goToAddAlarmGroupPage = () => {
  console.log('Navigating to add alarm group page');
  router.push({path: '/settings/alarm-config/edit'}); 
};

// 跳转到编辑报警地址组页面
const goToEditAlarmGroupPage = (groupId) => {
  console.log('Navigating to edit alarm group page for ID:', groupId);
  router.push({path: `/settings/alarm-config/edit/${groupId}`}); 
};

// 跳转到删除确认页面
const goToDeleteAlarmGroupConfirmPage = (groupId, addressName) => {
  console.log(`Preparing to delete alarm group ID: ${groupId}, Address: ${addressName}`);
  router.push({
    path: `/settings/alarm-config/delete/${groupId}`,
    query: { address: addressName }
  });
};


// --- 生命周期钩子 ---
onMounted(() => {
  console.log('Alarm Config Page mounted');
  // 加载报警地址组数据
  loadAlarmGroups();
});

// onUnmounted 钩子通常不需要，除非有全局事件监听或定时器需要清理
// onUnmounted(() => { });

// ESC键返回功能可以通过 Vue Router 的 beforeEach 或组件内部监听实现
// 如果需要在单个组件内实现ESC返回，可以在 mounted 中添加监听，在 unmounted 中移除
onMounted(() => {
  const handleEscape = (event) => {
    if (event.key === 'Escape') {
      router.back(); // 使用 router.back() 返回上一页
    }
  };
  document.addEventListener('keydown', handleEscape);
  onUnmounted(() => {
    document.removeEventListener('keydown', handleEscape);
  });
});

</script>

<style scoped>
/* --- 将原始 HTML 文件中的所有自定义样式复制到这里 --- */

/* --- Inherited Styles & Color Palette --- */
/* 根变量通常在全局 CSS 中定义，但为了完整性，这里列出 */
/* :root {
  --bg-primary: #f3f4f6;
  --bg-secondary: #ffffff;
  --text-primary: #1f2937;
  --text-secondary: #6b7280;
  --text-tertiary: #9ca3af;
  --border-color: #e5e7eb;
  --accent-blue: #3b82f6;
  --status-green: #22c55e;
  --status-yellow: #eab308;
  --status-red: #ef4444;
  --status-gray: #6b7280;
  --status-off: #9ca3af;
  --online-green: #10b981;
  --offline-red: #f43f5e;
  --alarm-color: var(--status-red);
} */

/* body 样式通常由父组件或全局 App.vue 控制 */
/* body {
  font-family: 'Inter', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
} */

/* --- Header (Consistent) --- */
/* Header 样式已移至 AppHeader.vue 或全局 */


/* --- Main Content Area --- */
main {
  flex-grow: 1;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* Prevent main from scrolling, let table handle it */
  gap: 1rem;
}

.page-title {
  font-size: 1.1rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 0;
  text-align: center;
  flex-shrink: 0;
}

/* --- Top Bar (Search & Add Button) --- */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
  flex-shrink: 0;
}

.filter-input-container {
  position: relative;
  width: 250px;
}

.filter-input-container i {
  position: absolute;
  left: 0.75rem;
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-tertiary);
  font-size: 0.9rem;
}

#alarm-group-search {
  padding: 0.4rem 0.75rem 0.4rem 2.25rem;
  border: 1px solid var(--border-color);
  border-radius: 0.375rem;
  font-size: 0.8rem;
  background-color: var(--bg-secondary);
  width: 100%;
}

#alarm-group-search:focus {
  outline: none;
  border-color: var(--accent-blue);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
}

.hmi-button {
  padding: 0.4rem 0.8rem;
  border-radius: 0.375rem;
  font-size: 0.8rem;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.3rem;
  border: 1px solid transparent;
  transition: all 0.2s ease;
  cursor: pointer;
}

.hmi-button i {
  font-size: 0.9em;
}

.hmi-button-primary {
  background-color: var(--accent-blue);
  color: white;
  border-color: var(--accent-blue);
}

.hmi-button-primary:hover {
  background-color: #2563eb;
  border-color: #2563eb;
}

.hmi-button-danger {
  background-color: var(--status-red);
  color: white;
  border-color: var(--status-red);
}

.hmi-button-danger:hover {
  background-color: #dc2626;
  border-color: #dc2626;
}


/* --- Alarm Detail Table Area --- */
.alarm-table-container {
  flex-grow: 1;
  overflow: auto; /* Enable both horizontal and vertical scroll */
  background-color: var(--bg-secondary);
  border-radius: 0.5rem;
  border: 1px solid var(--border-color);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.alarm-table {
  width: 100%;
  min-width: 1200px; /* Ensure minimum width for all bit columns */
  border-collapse: collapse; /* Use solid border for grid look */
  font-size: 0.7rem; /* Smaller font for more content */
}

.alarm-table th, .alarm-table td {
  padding: 0.4rem 0.5rem; /* Reduced padding */
  text-align: left;
  border: 1px solid var(--border-color); /* Use solid border for grid look */
  vertical-align: top; /* Align content top */
}

.alarm-table th {
  background-color: #f9fafb;
  font-weight: 600;
  color: var(--text-secondary);
  position: sticky; /* Keep header sticky */
  top: 0;
  z-index: 10;
  text-align: center;
  white-space: nowrap;
}

.alarm-table td {
  height: 40px; /* Give cells some minimum height */
  line-height: 1.3;
}

.alarm-table tbody tr:hover {
  background-color: #f0f4f8;
}

/* Specific column styles */
.col-address {
  width: 80px;
  font-weight: 600;
  font-family: 'Courier New', Courier, monospace;
  background-color: #f9fafb; /* Keep bg color for distinction */
}

.col-category {
  width: 100px;
  background-color: #f9fafb; /* Keep bg color */
}

.col-bit {
  width: 150px;
  /* Cells for bit descriptions can wrap */
  white-space: normal;
  word-break: break-all;
}

/* Width for bit description columns */
.col-actions {
  width: 80px;
  text-align: center;
  vertical-align: middle;
  background-color: #f9fafb; /* Keep bg color for distinction */
}

/* Action Buttons in Table */
.action-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.2rem;
  font-size: 0.9rem;
  margin: 0 0.2rem;
  transition: color 0.2s ease;
}

.action-button.edit {
  color: var(--accent-blue);
}

.action-button.edit:hover {
  color: #2563eb;
}

.action-button.delete {
  color: var(--status-red);
}

.action-button.delete:hover {
  color: #dc2626;
}

/* Highlight rows matching filter */
.alarm-table tbody tr.highlight {
  background-color: #e0f2fe; /* Light blue highlight */
}

/* Original body inline styles - Should be managed in App.vue or layout */
/* body[style="max-width: 800px; max-height: 600px; margin: auto;"] */
/* Remove or adapt these in your App.vue or main layout component */

</style>